import { listen, TauriEvent } from '@tauri-apps/api/event';
import type { UnlistenFn } from '@tauri-apps/api/event';
import { open } from "@tauri-apps/api/dialog"
import { useConfigStore } from '@/store/config'
import { onMounted, onUnmounted } from 'vue';
import { getFileSuffix } from '@/utils/file'
import { OnOpenFiles } from './index';

export default ({ onOpenFiles } : { onOpenFiles: OnOpenFiles }) => {

  const configStore = useConfigStore()
  const { fileConfig } = toRefs(configStore)

  // 打开文件
  const openFileDialog = () => {
    open({
      title: '请选择视频文件',
      multiple: true,
      filters: [{name: '请选择', extensions: fileConfig.value.types }]
    }).then(res => {
      if (res == null) {
        console.log('取消文件选择')
        // 点击取消了
      } else {
        onOpenFiles(res as string[]);
      }
    }).catch(err => {
      console.log(err)
    })
  }

  let unFileDrop : UnlistenFn;
  onMounted(async () => {
    // 监听拖动文件到窗口事件
    unFileDrop = await listen<string[]>(TauriEvent.WINDOW_FILE_DROP, (event) => {
      console.log(event)
      const files = event.payload.filter(item => {
        const suffix = getFileSuffix(item);
        return suffix && fileConfig.value.types.includes(suffix.toLowerCase())
      })
      files.length > 0 && onOpenFiles(files)
    })
  })
  onUnmounted(() => {
    unFileDrop && unFileDrop()
  })

  return {
    openFileDialog
  }
}
